﻿using EIP.Authorize.Logic.Models;
using EIP.Authorize.Logic.Repository;
using EIP.Common.Models;
using EIP.Common.Util;
using System.Threading.Tasks;

namespace EIP.Authorize.Logic.Logic.Impl
{
    /// <summary>
    /// 登录业务逻辑
    /// </summary>
    public class AccountLogic : IAccountLogic
    {
        #region 构造函数

        private readonly IAccountRepository _accountRepository;
        /// <summary>
        /// 登录业务逻辑
        /// </summary>
        /// <param name="accountRepository"></param>
        public AccountLogic(IAccountRepository accountRepository)
        {
            _accountRepository = accountRepository;
        }

        #endregion
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<OperateStatus<LoginOutput>> Login(LoginInput input)
        {
            //将传入的密码加密
            var encryptPwd = DEncryptUtil.Encrypt(input.Password, ConfigurationUtil.GetSection("EIP:PasswordKey"));
            //查询信息
            input.Password = encryptPwd;

            var data = await _accountRepository.Login(input);

            //是否存在
            if (data == null)
            {
                return OperateStatus<LoginOutput>.Error("用户名或密码错误");
            }
            //是否冻结
            if (data.IsFreeze)
            {
                return OperateStatus<LoginOutput>.Error("登录用户已冻结");
            }
            //更新用户最后一次登录时间
            await _accountRepository.UpdateTime(data.UserId);
            data.LoginId = CombUtil.NewComb();
            return OperateStatus<LoginOutput>.Success(data);
        }
    }
}